package com.lpy.book.model;



import com.mysql.jdbc.Connection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

// 使用单例模式进行连接数据库
public class DbUtil {
    private volatile static DataSource dataSource = null;

    // 建立数据源
    private static DataSource getDataSource() {
        if (dataSource == null) {
            synchronized (DbUtil.class) {
                if (dataSource == null) {
                    dataSource = new MysqlDataSource();
                    ((MysqlDataSource) dataSource).setURL("\"jdbc:mysql://127.0.0.1:3306/blog_system?characterEncoding=utf8&&useSSL=false\"");
                    ((MysqlDataSource) dataSource).setUser("root");
                    ((MysqlDataSource) dataSource).setPassword("llt050201");
                }
            }
        }
        return dataSource;
    }

    // 建立连接
    public static Connection getConnection() throws SQLException {
        return (Connection) getDataSource().getConnection();
    }

    // 关闭资源
    public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet) throws SQLException {
        if(resultSet != null) {
            resultSet.close();
        }

        if(statement != null) {
            statement.close();
        }

        if(connection != null) {
            connection.close();
        }
    }


}
